package handlers

import (
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"quiz-master/cache"
	"quiz-master/model"
	"strconv"
	"time"
)

func PerSonList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	/*
		     SELECT
			pser_son_orders.id as OrderId,
			per_sons.per_code as PerCode,
			per_sons.per_name as PerName,
			per_sons.per_phone as PerPhone,
			pser_son_orders.order_code as OrderCode,
			pser_son_orders.order_to as OrderTo
			FROM pser_son_orders
			LEFT JOIN per_sons on per_sons.id=pser_son_orders.pid
	*/
	var list []model.PerSonOrderList
	redis_key := "redis_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("pser_son_orders").
			Select(
				"pser_son_orders.id as OrderId",
				"per_sons.per_code as PerCode",
				"per_sons.per_name as PerName",
				"per_sons.per_phone as PerPhone",
				"pser_son_orders.order_code as OrderCode",
				"pser_son_orders.order_to as OrderTo",
			).
			Joins("LEFT JOIN per_sons on per_sons.id=pser_son_orders.pid").
			Offset(offset).
			Limit(size).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var count int64
	model.DB.Model(&model.PserSonOrder{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"count": count,
	})

}

func PerSonOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var list model.PerSonOrderList
	redis_key := "redis_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("pser_son_orders").
			Select(
				"pser_son_orders.id as OrderId",
				"per_sons.per_code as PerCode",
				"per_sons.per_name as PerName",
				"per_sons.per_phone as PerPhone",
				"pser_son_orders.order_code as OrderCode",
				"pser_son_orders.order_to as OrderTo",
			).
			Joins("LEFT JOIN per_sons on per_sons.id=pser_son_orders.pid").
			Where("pser_son_orders.id = ?", id).
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})

}
